package com.cy.pj.health;


import com.cy.pj.module.pojo.ResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

//@Controller
//@ResponseBody
@RestController //  ==  @ResponseBody + @Controller
public class JsonController {

    @RequestMapping("/doConvertResponseToJson")
    @ResponseBody
    public ResponseResult doConvertResponseToJson(){
        ResponseResult result = new ResponseResult();
        result.setCode(200);
        result.setMessage("???");
        return result;

    }

    /**
     * //当使用@ResponseBody此注解描述控制层的handler方法时，假如此方法的返回值为
     * map或pojo这样对象，系统地城会将这样的转换为json格式字符串，然后相应到客户端
     * @return
     */

    @RequestMapping("/doConvertMapToJson")
    //@ResponseBody
    public Map<String, Object> doConvertMapToJson(){
        Map<String, Object> map = new HashMap<>();
        map.put("state",1);
        map.put("message","ok");
        return map;
    }

    @RequestMapping("/doPrintJsonToClient01")
   // @ResponseBody
    public String doPrintJsonToClient01() throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        map.put("state",1);
        map.put("message","ok");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr=objectMapper.writeValueAsString(map);
        System.out.println("jsonStr = " + jsonStr);

        return jsonStr;
    }

    @RequestMapping("/doPrintJsonToClient02")
   // @ResponseBody
    public void doPrintJsonToClient02(HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("state",0);
        map.put("message","零");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr=objectMapper.writeValueAsString(map);
        System.out.println("jsonStr = " + jsonStr);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charse=utf-8");
        PrintWriter out = response.getWriter();
        out.println(jsonStr);
        out.flush();
    }
}
